import { ElMessage, ElMessageBox } from 'element-plus'
import { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import { TreePropsType } from '@/api/types/common'

/**
 * 通过class获取父节点
 * @param node 当前节点
 * @param parentTagName 父节点class
 */
export function findParentElement(node, parentTagName: string) {
  if (!node.parentNode) {
    return null // 到达根元素仍未找到指定父元素
  }
  const parentNodeClassName = node.parentNode.className
  const parentNodeClassNameAry = parentNodeClassName.split(' ')
  if (parentNodeClassNameAry.length > 1) {
    if (parentNodeClassNameAry.includes(parentTagName)) {
      return node.parentNode // 找到指定父元素
    }
  } else {
    if (parentNodeClassName === parentTagName) {
      return node.parentNode // 找到指定父元素
    }
  }
  return findParentElement(node.parentNode, parentTagName) // 继续向上查找父元素
}

/**
 * 防抖函数
 * @param {*} fn 方法
 * @param {*} delay 延时执行时间
 * @param {*} immdiate 是否初始化执行
 * @returns
 */
export function debounce(fn: () => void, delay = 500, immdiate = false) {
  let timer = null
  let isInvoke = false
  function _debounce(...arg) {
    if (timer) clearTimeout(timer)
    if (immdiate && !isInvoke) {
      fn.apply(this, arg)
      isInvoke = true
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arg)
        isInvoke = false
        timer = null
      }, delay)
    }
  }

  // 取消功能
  _debounce.cancel = function () {
    if (timer) clearTimeout(timer)
    timer = null
    isInvoke = false
  }
  return _debounce
}

/**
 * 操作成功提示
 * @param message 提示信息
 */
export function MsgError(message: string) {
  ElMessage.error(message)
}
export function MsgWarn(message: string) {
  ElMessage.warning(message)
}
export function MsgConfirm(
  message: string,
  succFun?: () => any,
  errFun?: () => any,
) {
  ElMessageBox.confirm(message, '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => succFun && succFun())
    .catch(() => errFun && errFun())
}
export async function MsgConfirmAsync(message: string) {
  try {
    await ElMessageBox.confirm(message, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    return true
  } catch {
    return false
  }
}

/**
 * 失败提示
 * @param message 提示信息
 */
export function MsgSuccess(message: string) {
  ElMessage.success(message)
}

export function getUploadHttpUrl(url: string) {
  if (/http/.test(url) && /file/.test(url)) {
    const [baseUrl, resUrl] = url.split('/file')
    console.log(baseUrl)
    return '/file' + resUrl
  }
  return url
}

export function randomString(length: number) {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  return Array.from(
    { length },
    () => characters[Math.floor(Math.random() * characters.length)],
  ).join('')
}

/**
 * 数据转化成树结构
 * @param data
 * @param parentId
 * @param prop
 */
export function arrToTree(data: any[], parentId = null, prop?: TreePropsType) {
  const props: TreePropsType = {
    id: prop?.id || 'id',
    parentId: prop?.parentId || 'parentId',
    label: prop?.label || 'label',
  }
  const tree = []
  for (const item of data) {
    if (item[props.parentId!] === parentId) {
      const children = arrToTree(data, item[props.id!], prop)
      if (children.length > 0) {
        item.children = children
      }
      tree.push(item)
    }
  }
  return tree
}


/**
 * 路由跳转
 * @param router
 * @param routeName
 * @param params
 */
export function navigateToRoute( router: Router,routeName: string,params?: Record<string, any>) {
  const route: RouteLocationNormalizedLoaded = {
    name: routeName,
    params: params,
  };
  router.push(route).catch(err => {
    // 处理路由跳转失败的情况
    console.error('Failed to navigate to route', err);
  });
}
